<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../../../lib/layui-v2.6.3/css/layui.css" media="all">
    <link rel="stylesheet" href="../../../css/public.css" media="all">
    <style>
        body {
            background-color: #ffffff;
        }
    </style>
</head>
<body>
<div>
    <div>
        <div style="display: flex">
            <div id="download-template" style="padding-left: 10px;">
                <button type="button" class="layui-btn downloadTemplate">
                    下载模板
                </button>
            </div>
            <div style="padding-left: 20px;" id="upload-data">
                <button type="button" class="layui-btn" id="uploadData">
                    <i class="layui-icon">&#xe67c;</i>导入数据
                </button>
            </div>
        </div>
    </div>
    <!--数据预览-->
    <div id="importDataPreviewPopup" style="display: none">
        <table style="width:100%;" id="dataPreviewTable" lay-filter="dataPreviewTable"></table>
    </div>
</div>
</body>
<script src="../../../lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
<script src="../../../lib/jquery-3.4.1/jquery-3.4.1.min.js" charset="utf-8"></script>
<script src="../../../lib/SheetJS/xlsx.full.min.js" charset="utf-8"></script>
<script src="../../../lib/common/common.js" charset="utf-8"></script>
<script>
    /**
     * {
     *     module:模块
     *     templateName:模板名称
     *     param:参数
     *     errDataFile: {}
     *     errTemplateName : 失败模板名称
     *     dataPreviewUrl :  数据预览路径，相对于父组件
     * }
     */

    let paramData;

    //子窗口接受参数
    function childParam(resDate) {
        if (!isNotNull(resDate.module) || !isNotNull(resDate.templateName)) {
            layer.msg('所属模块和模板名称不能为空');
            setTimeout(function () {
                let iframeIndex = parent.layer.getFrameIndex(window.name);
                parent.layer.close(iframeIndex);
            }, 1500);
        }
        if (!isNotNull(resDate.dataPreviewUrl)) {
            layer.msg('数据预览界面路径不能为空');
            setTimeout(function () {
                let iframeIndex = parent.layer.getFrameIndex(window.name);
                parent.layer.close(iframeIndex);
            }, 1500);
        }
        paramData = resDate;
    }

    layui.use(['form', 'table', 'layer'], function () {
        var $ = layui.jquery,
            table = layui.table;

        // 监听下载模板按钮
        $('.downloadTemplate').click(function () {
            downloadExcel(`/common/export/excel`, paramData.param, paramData.templateName ?? '导入模板名称.xlsx', 'POST')
        })


        $('#uploadData').click(function () {
            // 预览上传的数据
            let fileInput = $('<input type="file">');
            fileInput.on('change', function (e) {
                let uploadFile = e.target.files[0];
                let reader = new FileReader();
                reader.onload = function (e) {
                    // 处理数据
                    let data = new Uint8Array(e.target.result);
                    let workbook = XLSX.read(data, {type: 'array'});
                    let sheetName = workbook.SheetNames[0];
                    let worksheet = workbook.Sheets[sheetName];
                    let json = XLSX.utils.sheet_to_json(worksheet, {header: 1});
                    let header = json[0];
                    // 处理table的表头和数据
                    let i = -1;
                    let headerDate = header.map(function (col) {
                        i++;
                        return {field: i, title: col, align: 'center', minWidth: 120};
                    })
                    let body = json.slice(1);
                    // 创建弹出层
                    // 获取父窗口
                    let parentWindow = window.parent;
                    parentWindow.layer.open({
                        type: 2,
                        title: '数据预览',
                        content: paramData.dataPreviewUrl,
                        area: ['100%', '100%'],
                        btn: ['确定', '取消'],
                        yes: function () {
                            var uploadMsg = parentWindow.layer.msg("数据处理中...", {
                                icon: 16,
                                time: -1
                            })
                            let formData = new FormData();
                            // 将文件添加到表单数据对象中
                            formData.append('file', uploadFile);
                            $.ajax({
                                type: "POST",
                                url: `/common/import/excel/${paramData.module}`,
                                dataType: 'json',
                                data: formData,
                                processData: false,
                                contentType: false,
                                success: function (req) {
                                    parentWindow.layer.close(uploadMsg);//手动关闭
                                    if (req.code === '200') {
                                        let errDate = req.data;
                                        if (errDate.length === 0) {
                                            layer.msg("数据更新成功");
                                            setTimeout(function () {
                                                parentWindow.layer.closeAll();
                                            }, 1500);
                                        } else {
                                            parentWindow.layer.msg("导入成功，部分数据处理失败,已自动下载失败数据，请查看！！！");
                                            setTimeout(function () {
                                                let myMsg = parentWindow.layer.msg("正在下载...", {
                                                    icon: 16,
                                                    time: -1
                                                })
                                                listTurnExcel({
                                                    id: "编号",
                                                    errMsg: "错误信息"
                                                }, errDate, paramData?.errTemplateName ?? '导入失败数据.xlsx')
                                                parentWindow.layer.close(myMsg);//手动关闭
                                                parentWindow.layer.closeAll();
                                            }, 2000);
                                        }
                                    } else {
                                        if (req.code === '600') {
                                            parentWindow.layer.msg(req.msg);
                                        } else {
                                            parentWindow.layer.close(uploadMsg);//手动关闭
                                            parentWindow.layer.msg("导入失败，请重试");
                                        }
                                    }
                                },
                                error: function (e) {
                                    parentWindow.layer.msg("数据有误");
                                }
                            })
                        },
                        success: function (layero, index) {
                            // 获取子页面的window对象
                            let childWin = layero.find("iframe")[0].contentWindow;
                            // 将参数传递给子页面
                            childWin.renderTable(headerDate, body);
                        },
                        end: function () {
                            parentWindow.layer.closeAll()
                        }
                    });
                };
                reader.readAsArrayBuffer(uploadFile);
            });
            fileInput.click();
        })
    })
</script>
</html>